<?php

namespace module\manage\controller;

use app\Controller;
use app\model\auth\Admin as Model;
use app\helper\Ident;
use app\model\auth\Menu;

class Visitor extends Controller
{
    /**
     * 密码登录.
     * 
     */
    public function login()
    {
        $model = Model::where('mobile', input('post.account/s'))->field(['id', 'name', 'password', 'status', 'mobile', 'avatar', 'role_id'])->findOrEmpty();
        if($model->isEmpty()){
            return json(['code' => 0, 'msg' => '当前用户不存在']);
        }
        if($model->status !== 2){
            return json(['code' => 0, 'msg' => '当前账户异常']);
        }
        if(!password_verify(input('post.password/s'), $model->password)){
            return json(['code' => 0, 'msg' => '密码错误']);
        }
        $role = $model->role;
        // 获取token
        $token = Ident::token(['uid' => $model->id, 'account' => input('post.account/s')]);
        //参数为用户认证的信息，请自行添加
        return json([
            'token' => $token,
            'menus' => Menu::tree(),
            'role_name' => $role->name,
            'roles' => $role->perms,
            'expires' => (time() + 3600 * 24 * 7) * 1000
        ] + $model->toArray());
    }
    /**
     * 短信登录.
     * 
     */
    public function sms()
    {
        // 获取token
        $model = Model::where('mobile', input('post.mobile/s'))->find();
        if(empty($model)){
            return json(['code' => 0, 'msg' => '当前用户不存在']);
        }
        $data = ['access_token' => Ident::token(['uid' => $model->id, 'account' => input('post.account/s')])]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['access_token'], $data + ['login_at' => time()]);
        return json($data);
    }
    /**
     * 注册.
     * 
     */
    public function signup()
    {    
        $model = new Model;
        $model->signup(input('post.'));
        return json([
            'access_token' => Ident::token(['id' => $model->id, 'account' => input('post.account/s')], config('jwt.key'), config('jwt.method'))
        ]);
    }
    /**
     * 重置密码.
     * 
     */
    public function forget()
    {
        // 获取token
        $model = Model::where('mobile', input('post.mobile/s'))->findOrFail();
        $model->password = md5(input('post.password/s'));
        $model->save();
        $data = ['access_token' => Ident::token(['uid' => $model->id, 'account' => input('post.account/s')])]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['access_token'], $data + ['login_at' => time()]);
        return json($data);
    }
}
